#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <cerrno>
#include <cstring>

using namespace std;

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl");
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);

    cout << "set" << fd << "nonblock done" << endl;
}

int main()
{
    char buffer[100];
    SetNonBlock(0);
    sleep(1);
    while (true)
    {
        ssize_t n = read(0, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            cout << "echo:" << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            // n < 0，出错了！
            // 这里我们就要判断：真出错？还是“非阻塞状态下，没数据可读”？
            if (n = EWOULDBLOCK)
            {
                // 不是出错，是没有数据可读
                cout << "0 fd data not ready, try again!" << endl;
                sleep(1);
            }
            else
            {
                // read出错
                cerr << "read error, n = " << n << "errno code: "
                     << errno << ", error str: " << strerror(errno) << endl;
            }
        }
    }
    return 0;
}